/**
   FRAMELOADER :: CORE
   Requetes automatiques en Ajax 

   (c) 2009 - _expressiv

**/

var FlFormHeader = 'application/x-www-form-urlencoded;ISO-8859-1';

var frameLoader = new Class({

    /** Gestion des options **/
    options: {
	Container        : 'Inner',         /*L'élément qui est mis à jour*/
	Overlay          : false,           /*Utilise-t-on un Overlay ?   */
	Icon             : false,           /*Nom de l'icone si il y a    */
	History          : true,            /*Affichage de l'URL histoy ? */
        FlashMenuId      : false,           /*Menu en flash si il y a     */
	DefaultPage      : '/Accueil.htm',  /*Page par défaut             */
	FlashEntete      : false,           /*Y-a-t-il une entete flash   */
	Actions          : [],              /*Action à lancer après req   */
	Title            : false,           /*Titre de la page            */
	killerActions    : []
    },

    /** Attributs */
    overlay  : null,
    milkbox : null,
    busy     : false,
    index    : 0,
    moduleKey: 0,
    stack    : [],

    /** Librairie des actions de base **/ 

    actions: {

	// Alist x Boolean -> MultiBox
	milkboxLoad : function(options,overlay){
	    /*Gestion du multibox*/
	    if (overlay) options.useOverlay = overlay;	
		//options.OS = Browser.Platform.name;
		//	    options.mbClass = '.mb';
	    return new Milkbox({ resizeTransition:'back:out', topPosition:30 });
	},

	// ( () -> () ) -> ( Event -> () )
	stopEvThen : function(fct){
	    return function(e){if (e) e.stop();
			       fct();};
	},

	// Element -> Boolean
	bAjaxLink : function(el){
	    return !(!el.href || 
		     ['lightbox','mb','nonFrame'].contains(el.rel) ||
		     el.hasClass("nonFrame") ||
		     el.hasClass("mb")||el.hasClass("internLink")||el.hasClass('bb_a_url')||el.hasClass('makePopup') ||
		     el.href.search(/mailto/)!=-1 ) &&
		( el._allerA==undefined && el.href.search(/\#/)== -1 );
	},

	// Element -> () :: EDB
	splitAnchor : function(el){
	    var anc = el._allerA.split('#');
	    el._allerA = anc[0];
	    el.href    = '#' + anc[1];
	},

	// Element -> () :: EDB
	elSplitRel : function(el){
	    var temp = el.rel.split(':');
	    if (temp[0]!='background') return ;
	    el.bg = temp[1];
	    el.rel = '';
	} ,

	// Url x Identifier [x String x Element] -> Request.HTML 
	getAjaxObject : function(urlR,targetR,methodR,dataR,killer){
	    if (!methodR) methodR='post';
	    if (killer)
		result = function(){
		    if (this.options.Overlay)
			this.options.Overlay.stop();
		    if (this.options.Icon)
			this.actions.iconHide(this.options.Icon);
		    this.busy = false;	
		    this.launchKillerActions();
		}.bind(this);
	    else result = function() {
		if (this.options.Overlay)
		    this.options.Overlay.stop();
		if (this.options.Icon)
		    this.actions.iconHide(this.options.Icon);
		this.busy=false;
         	this.launchActions();
		this.scanLink(targetR);
	        window.fireEvent('onFrameLoad');
		window.removeEvents('onFrameLoad');
		window.fireEvent('onFrameLoadAlways');
	    }.bind(this);
	    var dict = {url:urlR,
			method: methodR,
			update : $(targetR),
			data:dataR,
			onSuccess : result};
	    if (killer){r= new Request(dict);}
	    else{
		r = new Request.HTML(dict);
	    }
	    if (dataR) r.setHeader('Content-Type',FlFormHeader);
	    return r;
	},

	// Url x Boolean -> ()
	flashChangeMenu : function (lien){
	    if (typeof($(this.options.FlashMenuId).changeMenu) == "function")
		$(this.options.FlashMenuId).changeMenu(lien);
	},

	// Identifier -> () :: EDB
	iconShow : function (icon){$(icon).setStyle('display','block');},
	iconHide : function (icon){$(icon).setStyle('display','none');},

	// Identifier -> () :: EDB
	overlayShow : function (overlay){overlay.show();},
	overlayHide : function (overlay){overlay.hide();},

	// () -> [String]
	getModAndKELink : function(){
	    var link = this.History.getCurrentLocation().substring(1).split('.')[0];
	    return [link.split('/')[0],link];
	},

	// Element -> ()
	makeNewpageLink : function(el){
	    el.addEvent('click',this.actions.stopEvThen(function(){
		window.open(arguments[0],"");
	    }.pass(el.href)));
	    el.rel = "alreadyLink";
	},

	// Element -> ()
	makeXHRLink : function(el,target){
	    if (!target) target = this.options.Container;
	    el.rel = "noMoreAjax";
	    el._allerA = el.href;
	    if (el._allerA.indexOf('#') != -1) this.actions.splitAnchor(el);
	    else  el.removeProperty("href");
	    if (el.rel!=undefined) this.actions.elSplitRel(el);
	    el.addEvent('click',this.actions.stopEvThen(function(el,author,target){
		//@@ correction
		if (el.bg) $('EnteteContainer').setStyle('background','url('+el.bg+')');
		var T = this.urlToArray(el._allerA);
		if (!(el.rel!='' && el.bg=='') && author!='flash'){
		    if (this.options.FlashEntete)
			$(this.options.FlashEntete).changeMenu(T['RawPath']);
		    if (!this.busy) this.fireEvent('onChanged',T["Complete"]);
		    this.changePage(T["Complete"],undefined,undefined,target);
		}
	    }.bind(this,[el,undefined,target])));
	},

	// Element -> ()
	makeXHRForm : function(el,target,currentLocation,killer){
            if (!currentLocation) currentLocation = this.History.getCurrentLocation();
	    if (!target) target = this.options.Container;
	    if (el.action == "") el.action = currentLocation;
	    el.action = this.urlToArray(el.action,".xml")["Complete"];
	    el.addEvent('submit',this.actions.stopEvThen(function(el,target,killer){
		var T = this.urlToArray(el.action,".htm");
		if (!killer && !el.hasClass("refreshMyself")) this.fireEvent('onChanged',T["Complete"]);
		if (el.hasClass("refreshMyself")){
		    target = el.getParent();
		}
		this.changePage(T["Complete"],undefined,undefined,target,el.method,el,killer);
	    }.bind(this,[el,target,killer])));
	},

	makeXHRButton : function(el)
	{
	    var myForm = el.getParent('form');
	    var Inputs = myForm.getElements('input[type=submit]');
	    for (var i = 0;i < Inputs.length ; i++)
	    {
		if (Inputs[i] == el)
		{
		    el.set('readonly','readonly');
		}else{
		    Inputs[i].set('disabled','disabled');
		}
	    }
	    myForm.fireEvent('submit');
	},

	// Element -> ()
	makeSubXHRLink : function(el){
	    el._allerA = el.rel;
	    el.rel     = "noMoreAjax";
	    el.addEvent('click',this.actions.stopEvThen(function(){
		options = el._allerA.split('::');
		var T = this.urlToArray(options[0]);
		if (options[1] != "none")
		    var U = this.urlToArray(options[1]);
		else var U = "none";
		if (!this.busy)
		{
		    if (U != "none") this.fireEvent('onChanged',U["Complete"]);
		    this.options.Actions[this.options.Actions.length] = function(L)
		    {
			t = new Request.HTML({update:$('Ariane'),
					      url:"/Systeme/Interfaces/FilAriane/Ariane.htm",
					      onSuccess:function(){this.scanLink($('Ariane'));}.bind(this)
					     });
			t.get({"Module":L[0],"Chemin":L[1]});
			t.send();
			this.options.Actions.pop();
		    }.bind(this);
		}
		this.changePage(T["Complete"],undefined,undefined,options[2]);
	    }.bind(this)));
	}
    },

    // Alist x Alist -> ()
    initialize : function (options){
	this.setOptions(options);
	if (this.options.Title)
	    document.title = this.options.Title;
	//Historique
	this.History = new HistoryManager();
	this.History.addEvent('onHistoryChange',
			      function(hash){
				  if (!hash) hash=this.options.DefaultPage;
				  this.changePage(hash);
			      }.bind(this));
	this.addEvent('onChanged',function(lien){
	    this.History.addState(lien);
	}.bind(this)) ;
	window.addEvent('domready',function(){
	    var url = window.location.href;
	    var t = url.split('#');
	    if ($defined(t[1]))
	    {
		if (t[1].search(/htm/) == -1) return;
		Fl.changePage(t[1],true);
	    }
	});
    },

    prepareMb :function(milkboxOptions){
	if (this.options.MultiBox)
	    this.milkbox = this.actions.milkboxLoad(milkboxOptions);
    },

    // [x Identifier] -> ()
    scanLink : function(containerId,target,currentLocation,killer){
	var S;
	if (containerId) S = $(containerId);
	else S = document;
	S.getElements('a[rel=link]').each(
	    this.actions.makeNewpageLink.bind(this));
	this.milkbox.prepareGalleries(undefined,$$("a.mb"));
	this.milkbox.prepareEvents();
	S.getElements('a[rel!=noMoreAjax]').each(function(el){
	    if(!this.actions.bAjaxLink(el)) return;
	    this.actions.makeXHRLink.bind(this)(el,target);
	}.bind(this));
	//forme : rel = sous-url :: url :: target
	S.getElements('input[type=submit]').each(function(el){
	    el.addEvent('click',function(el){
		this.actions.makeXHRButton.bind(this,el)()}.bind(this,el));
	}.bind(this));
       	S.getElements("a[class=internLink]").each(function(el){
	    if (el.rel == "noMoreAjax") return;
	    this.actions.makeSubXHRLink.bind(this)(el);}.bind(this));
	S.getElements("form").each(function(el){
	    this.actions.makeXHRForm.bind(this)(el,target,currentLocation,killer);
	}.bind(this));
    },

    // Url [x Boolean x ? x Identifier x String x Element] -> () :: EDB
    changePage : function(lien,flash,init,target,arg2,arg3,killer){
	if (!lien) lien = this.History.getCurrentLocation();
	if (!lien) lien = this.urlToArray(document.location.href)["Complete"];
	if (this.busy && !killer) return ;
	    // TEMP

	    $$('textarea.mceEditor').each(function(el){
		if ($chk(el.getParent().getElement('span.mceEditor')))
		tinyMCE.execCommand('mceRemoveControl',false,el.get('id'));
	    });
	    $$('#mooRainbow').each(function(el){el.destroy()});
	    $$('.swiff-uploader-box').each(function(el){el.destroy()});

	if (!target) target=this.options.Container;
	if (this.options.FlashMenuId && !flash)
	    this.actions.flashChangeMenu(lien,flash).bind(this);
	if (this.options.Icon)
	    this.actions.iconShow(this.options.Icon);
	if (this.options.Overlay)
	    this.options.Overlay.start(target);
	    /*if (tinyMCE)
	{
	    $$('textarea.mceEditor').each(function(el){
		tinyMCE.execCommand('mceRemoveControl',false,el.get('id'));
	    });
	    }*/
	this.busy = true;
	Ajx = this.actions.getAjaxObject.bind(this,[lien,target,arg2,arg3,killer])();
	Ajx.send();
    },

    //  String x String -> String
    urlToArray : function(urlSend, suffix){
	var url     = urlSend;
	var result  = new Array();
	var rawPath = '';
	if (!suffix) suffix = '.htm';
	result["Raw"] = url;
	if (url.search(/http/) != -1)
	    url = '/' + url.split('/').slice(3).join('/');
	result["Relative"] = url;
	if (url.search(/\#/) != -1)
	{
	    var anchor = url.split('#');
	    url = anchor[0];
	    result["Anchor"] = anchor[1];
	}
	if (url.search(/\?/) != -1)
	{
	    var temp = url.split('?');
	    url = temp[0];
	    result["GetVars"] = temp[1];
	}
	rawPath = url;
	if (!['','/'].contains(url))
	    url = url.split('.')[0] + suffix;
	else if (url != undefined)
	    url += suffix;
	else
	    rawPath = '';
	result["RawPath"] = rawPath;
	result["Absolute"] = url;
	if (result["GetVars"]!=undefined) url+="?"+result["GetVars"];
	result["Complete"] =url;
	return result;
    },
    
    // () -> () :: EDB
    launchActions : function(){
	for (var i = 0; i < this.options.Actions.length; i++)
	    this.options.Actions[i](this.actions.getModAndKELink.bind(this)());
    },

    launchKillerActions : function(){
	for (var i = 0; i < this.options.killerActions.length; i++)
	    this.options.killerActions[i](this.actions.getModAndKELink.bind(this)());
    },

    // (String -> () ) -> () :: EDB
    addToLoad : function(fct,popup){
	if (popup) 	window.addEvent('onPopupLoad',fct);
	else window.addEvent('onFrameLoad',fct);
    },

    quickChange : function(params){
	lien = this.History.getCurrentLocation();
	if (!lien) lien = this.urlToArray(document.location.href)["Complete"];
	lien = lien + "?" + params;
	this.changePage(lien);
    }
});



//Initialisation du FrameLoader
frameLoader.implement(new Events);
frameLoader.implement(new Options);

window.addEvent('domready',function()
		{
		    window.fireEvent('onFrameLoad');
		    window.removeEvents('onFrameLoad');
		});
